有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中图像的swing平滑缩放

我创建了一个扩展Jbutton的按钮,并将其添加到按钮图像中,但这并不能使图像平滑。 我试过了,但没用

这是原始图像:

This is the origianl image

这就是它真正呈现画面的方式:

enter image description here

public class Button extends JButton {
private Image image;


public Button(Image image) {
    this.image = image;
}

public Image getImage() {
    return image;
}

public void setImage(Image image) {
    this.image = image;
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}

编辑:

我理解为什么它不能使图像平滑。 我不得不把drawImage改成g.drawImage(image, 0, 0, null);

我运行代码,有时它向我显示图片,有时它向我显示空方块,这向我显示控制台中的错误

只有我用鼠标移动它们,图片才会出现

enter image description here


共 (2) 个答案

  1. # 1 楼答案

    我不明白为什么要这么复杂
    我建议只创建一个ImageIcon并设置JButton图标
    示例代码:

    javax.swing.ImageIcon imgIco = new javax.swing.ImageIcon("path-to-icon-file");
    javax.swing.JButton button2 = new javax.swing.JButton(imgIco);
    button2.setPreferredSize(new java.awt.Dimension(imgIco.getIconWidth(), imgIco.getIconHeight()));
    

    上面代码的最后一行确保JButton大小与图标大小相同,因为您暗示这是您在对另一个答案的注释中想要的

  2. # 2 楼答案

    尝试以下方法。这是不言自明的

    public class CircleDisplay extends JPanel {
    
        final static int height = 500;
        final static int width = 500;
        Image img = null;
        JFrame frame = new JFrame();
    
        public static void main(String[] args) {
            new CircleDisplay();
        }
    
        public CircleDisplay() {
            Image img = null;
            try {
                img = ImageIO
                        .read(new File("f:yellowCircle.png"));
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
            frame.setDefaultCloseOperation(
                    JFrame.EXIT_ON_CLOSE);
            frame.add(this);
            img = 
                    img.getScaledInstance(50, 50,
                            Image.SCALE_SMOOTH);
            Button b = new Button(img);
            b.setPreferredSize(new Dimension(50,50));
    
            add(b);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    }
    
    class Button extends JButton {
        Image img;
        public Button(Image img) {
            this.img = img;
        }
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
    
            g.drawImage(img,0,0,null);
        }
    }